<template>
  <div class="project-game">
    <div class="game-header">
      <div class="header-content">
        <el-button icon="ArrowLeft" @click="goBack">返回游戏中心</el-button>
        <div class="game-title">
          <h1>📋 项目管理实战</h1>
          <p>规划项目，管理资源，按时交付高质量成果</p>
        </div>
        <div class="game-stats">
          <el-tag type="success" size="large">第 {{ currentWeek }}/12 周</el-tag>
          <el-tag type="warning" size="large">预算: ${{ budget }}k</el-tag>
          <el-tag type="danger" size="large">进度: {{ progress }}%</el-tag>
        </div>
      </div>
    </div>

    <div class="game-container">
      <!-- 开始界面 -->
      <div v-if="gameStatus === 'ready'" class="game-start">
        <div class="start-card">
          <el-icon class="start-icon"><Memo /></el-icon>
          <h2>项目管理实战</h2>
          <p>你接手了一个重要的软件开发项目，需要在12周内完成交付</p>
          <div class="game-rules">
            <h3>项目目标</h3>
            <ul>
              <li>项目预算：$500k</li>
              <li>项目周期：12周</li>
              <li>团队规模：5人</li>
              <li>需要完成：需求分析、设计、开发、测试、上线</li>
              <li>目标：按时、按预算、高质量交付</li>
            </ul>
          </div>
          <el-button type="primary" size="large" @click="startGame">
            <el-icon><CaretRight /></el-icon>
            开始项目
          </el-button>
        </div>
      </div>

      <!-- 游戏进行中 -->
      <div v-if="gameStatus === 'playing'" class="game-playing">
        <el-row :gutter="20">
          <!-- 左侧：项目概览 -->
          <el-col :span="16">
            <el-card class="project-overview">
              <template #header>
                <h3>📊 项目概览</h3>
              </template>
              
              <!-- 甘特图 -->
              <div class="gantt-chart">
                <h4>任务进度</h4>
                <div v-for="task in tasks" :key="task.id" class="task-row">
                  <div class="task-name">{{ task.name }}</div>
                  <div class="task-timeline">
                    <el-progress 
                      :percentage="task.progress" 
                      :status="task.status"
                      :color="task.color"
                    />
                  </div>
                  <div class="task-status">
                    <el-tag :type="getTaskTagType(task)" size="small">
                      {{ task.statusText }}
                    </el-tag>
                  </div>
                </div>
              </div>

              <!-- 团队状态 -->
              <div class="team-status">
                <h4>👥 团队状态</h4>
                <el-row :gutter="15">
                  <el-col :span="8" v-for="member in team" :key="member.id">
                    <div class="member-card">
                      <div class="member-info">
                        <el-avatar :size="50">{{ member.name[0] }}</el-avatar>
                        <div>
                          <div class="member-name">{{ member.name }}</div>
                          <div class="member-role">{{ member.role }}</div>
                        </div>
                      </div>
                      <el-progress 
                        type="circle" 
                        :percentage="member.workload" 
                        :width="60"
                        :color="member.workload > 100 ? '#f56c6c' : '#67c23a'"
                      />
                      <div class="member-task">{{ member.currentTask }}</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>

            <!-- 本周事件 -->
            <el-card class="week-events" v-if="weekEvents.length > 0">
              <template #header>
                <h3>⚠️ 本周事件</h3>
              </template>
              <el-timeline>
                <el-timeline-item 
                  v-for="event in weekEvents" 
                  :key="event.id"
                  :type="event.type"
                  :timestamp="event.day"
                >
                  <h4>{{ event.title }}</h4>
                  <p>{{ event.description }}</p>
                  <div v-if="event.options" class="event-options">
                    <el-button 
                      v-for="(option, index) in event.options" 
                      :key="index"
                      :type="option.type"
                      size="small"
                      @click="handleEventChoice(event, option)"
                    >
                      {{ option.text }}
                    </el-button>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </el-col>

          <!-- 右侧：决策面板 -->
          <el-col :span="8">
            <el-card class="decision-panel">
              <template #header>
                <h3>🎯 本周决策</h3>
              </template>

              <div class="project-metrics">
                <div class="metric-item">
                  <div class="metric-label">项目进度</div>
                  <el-progress :percentage="progress" :color="progressColor" />
                </div>
                <div class="metric-item">
                  <div class="metric-label">质量指标</div>
                  <el-progress :percentage="quality" :color="qualityColor" />
                </div>
                <div class="metric-item">
                  <div class="metric-label">团队士气</div>
                  <el-progress :percentage="morale" :color="moraleColor" />
                </div>
                <div class="metric-item">
                  <div class="metric-label">剩余预算</div>
                  <div class="budget-display">${{ budget }}k / $500k</div>
                </div>
              </div>

              <el-divider />

              <div class="action-section">
                <h4>本周行动</h4>
                <el-radio-group v-model="weeklyAction" class="action-radio">
                  <el-radio label="normal">正常开发</el-radio>
                  <el-radio label="overtime">加班赶进度 (-士气 +进度)</el-radio>
                  <el-radio label="training">团队培训 (-进度 +质量)</el-radio>
                  <el-radio label="review">代码审查 (-进度 +质量)</el-radio>
                  <el-radio label="teambuilding">团建活动 (-预算 +士气)</el-radio>
                </el-radio-group>
              </div>

              <el-divider />

              <div class="resource-section">
                <h4>资源分配</h4>
                <div v-for="task in tasks.filter(t => t.status === 'inProgress')" :key="task.id" class="task-resource">
                  <span>{{ task.name }}</span>
                  <el-input-number 
                    v-model="task.allocatedHours" 
                    :min="0" 
                    :max="40" 
                    :step="5"
                    size="small"
                  />
                  <span>小时</span>
                </div>
              </div>

              <div class="action-buttons">
                <el-button type="primary" size="large" block @click="nextWeek">
                  进入下一周
                </el-button>
              </div>
            </el-card>

            <el-card class="risk-panel">
              <template #header>
                <h3>⚡ 风险提示</h3>
              </template>
              <el-alert 
                v-for="risk in risks" 
                :key="risk.id"
                :title="risk.title"
                :type="risk.level"
                :description="risk.description"
                :closable="false"
                show-icon
                class="risk-item"
              />
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 游戏结束 -->
      <div v-if="gameStatus === 'finished'" class="game-finish">
        <div class="finish-card">
          <el-icon class="finish-icon" :class="finalGrade"><Trophy /></el-icon>
          <h2>项目完成！</h2>
          <div class="final-grade" :class="finalGrade">{{ finalGrade }} 级项目经理</div>
          <p class="grade-description">{{ gradeDescription }}</p>
          
          <div class="final-stats">
            <div class="stat-item">
              <div class="stat-label">项目进度</div>
              <div class="stat-value">{{ progress }}%</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">质量得分</div>
              <div class="stat-value">{{ quality }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">预算使用</div>
              <div class="stat-value">${{ 500 - budget }}k</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">团队士气</div>
              <div class="stat-value">{{ morale }}%</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">按时完成</div>
              <div class="stat-value">{{ onTime ? '是' : '否' }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">最终得分</div>
              <div class="stat-value highlight">{{ finalScore }}</div>
            </div>
          </div>

          <div class="action-buttons">
            <el-button type="primary" size="large" @click="restartGame">再玩一次</el-button>
            <el-button size="large" @click="goBack">返回游戏中心</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Memo, CaretRight, Trophy } from '@element-plus/icons-vue'

const router = useRouter()

const gameStatus = ref('ready')
const currentWeek = ref(1)
const budget = ref(500)
const progress = ref(0)
const quality = ref(80)
const morale = ref(80)
const weeklyAction = ref('normal')
const finalScore = ref(0)
const onTime = ref(false)

const tasks = ref([
  { id: 1, name: '需求分析', progress: 0, status: 'notStarted', statusText: '未开始', color: '#909399', allocatedHours: 0 },
  { id: 2, name: '系统设计', progress: 0, status: 'notStarted', statusText: '未开始', color: '#909399', allocatedHours: 0 },
  { id: 3, name: '前端开发', progress: 0, status: 'notStarted', statusText: '未开始', color: '#909399', allocatedHours: 0 },
  { id: 4, name: '后端开发', progress: 0, status: 'notStarted', statusText: '未开始', color: '#909399', allocatedHours: 0 },
  { id: 5, name: '测试', progress: 0, status: 'notStarted', statusText: '未开始', color: '#909399', allocatedHours: 0 },
  { id: 6, name: '部署上线', progress: 0, status: 'notStarted', statusText: '未开始', color: '#909399', allocatedHours: 0 }
])

const team = ref([
  { id: 1, name: '张三', role: '产品经理', workload: 80, currentTask: '需求分析' },
  { id: 2, name: '李四', role: '架构师', workload: 75, currentTask: '系统设计' },
  { id: 3, name: '王五', role: '前端工程师', workload: 90, currentTask: '待分配' },
  { id: 4, name: '赵六', role: '后端工程师', workload: 85, currentTask: '待分配' },
  { id: 5, name: '孙七', role: '测试工程师', workload: 60, currentTask: '待分配' }
])

const weekEvents = ref([])
const risks = ref([])

const progressColor = computed(() => progress.value < 50 ? '#f56c6c' : '#67c23a')
const qualityColor = computed(() => quality.value < 60 ? '#f56c6c' : '#67c23a')
const moraleColor = computed(() => morale.value < 50 ? '#f56c6c' : '#67c23a')

const finalGrade = computed(() => {
  if (finalScore.value >= 90) return 'S'
  if (finalScore.value >= 80) return 'A'
  if (finalScore.value >= 70) return 'B'
  if (finalScore.value >= 60) return 'C'
  return 'D'
})

const gradeDescription = computed(() => {
  const descriptions = {
    S: '卓越！你是一位出色的项目经理，完美地平衡了进度、质量和成本！',
    A: '优秀！项目交付成功，团队表现出色！',
    B: '良好！项目基本达到目标，但仍有改进空间。',
    C: '及格！项目勉强完成，需要提升项目管理能力。',
    D: '需要改进！项目管理存在明显问题。'
  }
  return descriptions[finalGrade.value]
})

const getTaskTagType = (task) => {
  if (task.status === 'completed') return 'success'
  if (task.status === 'inProgress') return 'primary'
  return 'info'
}

const startGame = () => {
  gameStatus.value = 'playing'
  // 初始化第一周
  tasks.value[0].status = 'inProgress'
  tasks.value[0].statusText = '进行中'
  tasks.value[0].color = '#409eff'
  tasks.value[0].allocatedHours = 20
  
  generateWeekEvents()
  updateRisks()
  ElMessage.success('项目启动！开始第一周工作')
}

const generateWeekEvents = () => {
  const events = [
    {
      id: 1,
      day: '周一',
      type: 'primary',
      title: '客户需求变更',
      description: '客户提出了新的功能需求',
      options: [
        { text: '接受变更', type: 'primary', effect: { budget: -20, progress: -5, quality: 5 } },
        { text: '拒绝变更', type: 'danger', effect: { quality: -10 } }
      ]
    },
    {
      id: 2,
      day: '周三',
      type: 'warning',
      title: '团队成员请假',
      description: '一名核心成员因病请假3天',
      options: [
        { text: '重新分配任务', type: 'primary', effect: { progress: -3, morale: -5 } },
        { text: '招聘临时人员', type: 'warning', effect: { budget: -10 } }
      ]
    }
  ]
  
  // 随机选择1-2个事件
  const selectedEvents = []
  const eventCount = Math.random() > 0.5 ? 2 : 1
  for (let i = 0; i < eventCount; i++) {
    if (events[i]) selectedEvents.push(events[i])
  }
  
  weekEvents.value = selectedEvents
}

const handleEventChoice = (event, option) => {
  // 应用效果
  if (option.effect.budget) budget.value += option.effect.budget
  if (option.effect.progress) progress.value += option.effect.progress
  if (option.effect.quality) quality.value += option.effect.quality
  if (option.effect.morale) morale.value += option.effect.morale
  
  // 移除事件
  weekEvents.value = weekEvents.value.filter(e => e.id !== event.id)
  ElMessage.success('决策已执行')
}

const updateRisks = () => {
  const riskList = []
  
  if (budget.value < 100) {
    riskList.push({ id: 1, title: '预算不足', level: 'error', description: '剩余预算不足20%，可能影响项目交付' })
  }
  
  if (morale.value < 50) {
    riskList.push({ id: 2, title: '团队士气低落', level: 'warning', description: '团队成员工作积极性下降，可能影响进度和质量' })
  }
  
  if (quality.value < 60) {
    riskList.push({ id: 3, title: '质量问题', level: 'error', description: '代码质量较低，后期可能需要大量返工' })
  }
  
  if (progress.value < (currentWeek.value / 12) * 100 - 10) {
    riskList.push({ id: 4, title: '进度滞后', level: 'warning', description: '项目进度落后于计划，可能无法按时交付' })
  }
  
  risks.value = riskList
}

const nextWeek = () => {
  // 根据本周行动更新指标
  const action = weeklyAction.value
  let progressDelta = 0
  let qualityDelta = 0
  let moraleDelta = 0
  let budgetDelta = 0
  
  switch (action) {
    case 'normal':
      progressDelta = 10
      qualityDelta = 2
      moraleDelta = 0
      budgetDelta = -30
      break
    case 'overtime':
      progressDelta = 15
      qualityDelta = -3
      moraleDelta = -10
      budgetDelta = -35
      ElMessage.warning('加班提升了进度，但影响了质量和士气')
      break
    case 'training':
      progressDelta = 5
      qualityDelta = 8
      moraleDelta = 5
      budgetDelta = -35
      ElMessage.success('培训提升了团队能力')
      break
    case 'review':
      progressDelta = 7
      qualityDelta = 10
      moraleDelta = -3
      budgetDelta = -32
      ElMessage.success('代码审查提升了质量')
      break
    case 'teambuilding':
      progressDelta = 8
      qualityDelta = 0
      moraleDelta = 15
      budgetDelta = -40
      ElMessage.success('团建活动提升了团队士气')
      break
  }
  
  // 应用资源分配的影响
  tasks.value.forEach(task => {
    if (task.status === 'inProgress' && task.allocatedHours > 0) {
      const taskProgress = (task.allocatedHours / 40) * progressDelta
      task.progress = Math.min(100, task.progress + taskProgress)
      
      if (task.progress >= 100) {
        task.progress = 100
        task.status = 'completed'
        task.statusText = '已完成'
        task.color = '#67c23a'
        
        // 自动开始下一个任务
        const nextTask = tasks.value.find(t => t.status === 'notStarted')
        if (nextTask) {
          nextTask.status = 'inProgress'
          nextTask.statusText = '进行中'
          nextTask.color = '#409eff'
          nextTask.allocatedHours = 20
        }
      }
    }
  })
  
  progress.value = Math.min(100, progress.value + progressDelta)
  quality.value = Math.max(0, Math.min(100, quality.value + qualityDelta))
  morale.value = Math.max(0, Math.min(100, morale.value + moraleDelta))
  budget.value = Math.max(0, budget.value + budgetDelta)
  
  // 更新团队工作负载
  team.value.forEach(member => {
    member.workload = 70 + Math.floor(Math.random() * 40)
  })
  
  currentWeek.value++
  
  if (currentWeek.value > 12) {
    finishGame()
  } else {
    generateWeekEvents()
    updateRisks()
    weeklyAction.value = 'normal'
  }
}

const finishGame = () => {
  onTime.value = currentWeek.value <= 12
  
  // 计算最终得分
  const progressScore = progress.value
  const qualityScore = quality.value
  const budgetScore = (budget.value / 500) * 100
  const moraleScore = morale.value
  const timeScore = onTime.value ? 100 : 50
  
  finalScore.value = Math.floor(
    (progressScore * 0.3 + qualityScore * 0.25 + budgetScore * 0.2 + moraleScore * 0.15 + timeScore * 0.1)
  )
  
  gameStatus.value = 'finished'
  ElMessage.success('项目结束！查看最终评估')
}

const restartGame = () => {
  gameStatus.value = 'ready'
  currentWeek.value = 1
  budget.value = 500
  progress.value = 0
  quality.value = 80
  morale.value = 80
  weeklyAction.value = 'normal'
  finalScore.value = 0
  onTime.value = false
  
  tasks.value.forEach(task => {
    task.progress = 0
    task.status = 'notStarted'
    task.statusText = '未开始'
    task.color = '#909399'
    task.allocatedHours = 0
  })
  
  weekEvents.value = []
  risks.value = []
}

const goBack = () => {
  router.push('/learning/games')
}
</script>

<style scoped>
.project-game {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.game-header {
  background: white;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.game-title {
  flex: 1;
  text-align: center;
}

.game-title h1 {
  margin: 0 0 5px 0;
  font-size: 24px;
}

.game-title p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.game-stats {
  display: flex;
  gap: 10px;
}

.game-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.game-start {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 600px;
}

.start-card {
  background: white;
  border-radius: 16px;
  padding: 50px;
  text-align: center;
  max-width: 600px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.start-icon {
  font-size: 80px;
  color: #409eff;
  margin-bottom: 20px;
}

.start-card h2 {
  margin: 0 0 15px 0;
  font-size: 32px;
}

.game-rules {
  text-align: left;
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin: 20px 0 30px;
}

.game-rules h3 {
  margin: 0 0 15px 0;
  font-size: 18px;
}

.game-rules ul {
  margin: 0;
  padding-left: 20px;
}

.game-rules li {
  margin-bottom: 8px;
  line-height: 1.6;
}

.game-playing {
  margin-top: 20px;
}

.project-overview h3,
.decision-panel h3,
.risk-panel h3,
.week-events h3 {
  margin: 0;
  font-size: 16px;
}

.gantt-chart,
.team-status {
  margin-bottom: 30px;
}

.gantt-chart h4,
.team-status h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
}

.task-row {
  display: grid;
  grid-template-columns: 150px 1fr 100px;
  gap: 15px;
  align-items: center;
  margin-bottom: 15px;
}

.task-name {
  font-weight: 500;
  color: #606266;
}

.member-card {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.member-name {
  font-weight: 500;
  font-size: 14px;
}

.member-role {
  font-size: 12px;
  color: #909399;
}

.member-task {
  font-size: 12px;
  color: #606266;
  text-align: center;
}

.week-events {
  margin-top: 20px;
}

.event-options {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.project-metrics {
  margin-bottom: 20px;
}

.metric-item {
  margin-bottom: 20px;
}

.metric-label {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.budget-display {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  text-align: center;
  padding: 10px;
  background: #ecf5ff;
  border-radius: 4px;
}

.action-section h4,
.resource-section h4 {
  margin: 0 0 15px 0;
  font-size: 15px;
  color: #303133;
}

.action-radio {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.task-resource {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-bottom: 10px;
}

.action-buttons {
  margin-top: 20px;
}

.risk-panel {
  margin-top: 20px;
}

.risk-item {
  margin-bottom: 10px;
}

.game-finish {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 600px;
}

.finish-card {
  background: white;
  border-radius: 16px;
  padding: 50px;
  text-align: center;
  max-width: 800px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.finish-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.finish-icon.S, .finish-icon.A {
  color: #f59e0b;
}

.finish-card h2 {
  margin: 0 0 20px 0;
  font-size: 32px;
}

.final-grade {
  display: inline-block;
  padding: 10px 30px;
  border-radius: 50px;
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 15px;
}

.final-grade.S {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
  color: #8b4513;
}

.final-grade.A {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.grade-description {
  margin: 0 0 30px 0;
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
}

.final-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.stat-item {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 20px;
  color: white;
}

.stat-label {
  font-size: 14px;
  margin-bottom: 10px;
  opacity: 0.9;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.highlight {
  font-size: 32px;
}

@media (max-width: 1200px) {
  .game-playing {
    display: block;
  }
  
  .final-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>

